package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;

import com.mmall.util.RedisShardedPoolUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Created by root on 3/18/18.
 */
@Service
public class UserServiceImpl implements IUserService{

    @Autowired
    private UserMapper userMapper;
    public ServerResponse<User> login(String userName, String password){

        /*ServerResponse response = validCheck(userName, Const.USERNAME);
        if (!response.isSuccess()){
            return response;
        }*/

        User user = userMapper.selectLogin(userName, password);
        if (user == null){
            return ServerResponse.createByError("password is wrong");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("login success", user);
    }

    public ServerResponse register(User user){
        if ( user == null){
            return  ServerResponse.createByError();
        }
        ServerResponse response = validCheck(user.getUsername(), Const.USERNAME);
        if (!response.isSuccess()){
            return response;
        }
        response = validCheck(user.getUsername(), Const.EMAIL);
        if (!response.isSuccess()){
            return response;
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        userMapper.insert(user);
        return ServerResponse.createBySuccess();
    }

    public ServerResponse validCheck(String value, String type){
        if (Const.USERNAME.equals(type)){
            if (StringUtils.isEmpty(value)){
                return ServerResponse.createByError("username is empty");
            }
            int rs = userMapper.checkUserName(value);
            if (rs > 0){
                return ServerResponse.createByError("username  exists");
            }
        }
        if (Const.EMAIL.equals(value)){
            if (StringUtils.isEmpty(value)){
                return ServerResponse.createByError("email is empty");
            }
            int rs = userMapper.checkEmail(value);
            if (rs > 0){
                return ServerResponse.createByError("email exists");
            }
        }

        return ServerResponse.createBySuccess();
    }

    public ServerResponse selectQuestion(String userName){
        ServerResponse response = validCheck(userName, Const.USERNAME);
        if (!response.isSuccess()){
            return response;
        }
       String question = userMapper.selectQuestion(userName);
        if (StringUtils.isEmpty(question)){
            return ServerResponse.createByError("there is no question");
        }
        return ServerResponse.createBySuccess(question);
    }

    public ServerResponse forgetCheckAnswer(String username, String question, String answer){
        int rs = userMapper.forgetCheckAnswer(username,question,answer);
        if (rs > 0){
            //generate a token to cache for validate that has answer the question and the answer is matched;
            String token = UUID.randomUUID().toString();
           // TokenCache.set(TokenCache.TOKEN_PREFIX + username, token);
            RedisShardedPoolUtil.set(TokenCache.TOKEN_PREFIX + username, token);
            RedisShardedPoolUtil.expired(TokenCache.TOKEN_PREFIX + username, Const.RedisCacheExTime.REDIS_QUESTION_TOKEN);
            return ServerResponse.createBySuccess(token);
        }
        return ServerResponse.createByError("answer not match the question");
    }

    public ServerResponse resetPassword(User user, String passwordOld, String passwordNew){

        if (user == null) {
            return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }

        User userSelect = userMapper.selectLogin(user.getUsername(), passwordOld);
        if (userSelect == null){
            return ServerResponse.createByError("old password is wrong");
        }
        int rs =userMapper.updatePwdByUserName(user.getUsername(),passwordNew);
        if (rs > 0){
            return ServerResponse.createBySuccess();
        } else {
            return ServerResponse.createByError("reset password failed, please try again");
        }
    }



    public ServerResponse<String> forgetResetPassword(String username, String newPsw, String forgetToken){
        if (StringUtils.isEmpty(forgetToken)){
            return ServerResponse.createByError("need token");
        }
        ServerResponse response = validCheck(username, Const.USERNAME);
        if (response.isSuccess()){
            return ServerResponse.createByError("username  not eixists");
        }

        //String token = TokenCache.get(TokenCache.TOKEN_PREFIX + username);
        String token = RedisShardedPoolUtil.get(TokenCache.TOKEN_PREFIX + username);

        if (StringUtils.isEmpty(token)){
            return ServerResponse.createByError("token is expird or unvalid");
        }
        if (!StringUtils.isEmpty(token) && token.equals(forgetToken)){
            int rs =userMapper.updatePwdByUserName(username,newPsw);
            if (rs > 0){
                return ServerResponse.createBySuccess();
            }
        } else {
            return ServerResponse.createByError("token is error,answer the question again");
        }
        return ServerResponse.createByError("reset new password fail, please try again");
    }


    public ServerResponse updateUserInfo(User userInfo){
        if (userInfo == null){
            return ServerResponse.createByError();
        }
        ServerResponse validResp = validCheck(userInfo.getEmail(), Const.EMAIL);
        if (!validResp.isSuccess()){
            return validResp;
        }
        User updateUser = new User();
        updateUser.setId(userInfo.getId());
        updateUser.setEmail(userInfo.getEmail());
        updateUser.setAnswer(userInfo.getAnswer());
        updateUser.setQuestion(userInfo.getQuestion());
        updateUser.setPhone(userInfo.getPhone());
        int rs = userMapper.updateByPrimaryKeySelective(updateUser);
        if (rs > 0){
            return ServerResponse.createBySuccess();
        } else {
            return ServerResponse.createByError("update user information failed, please try again");
        }
    }

    public ServerResponse getUserById(Integer userId){
        if (userId == null){
            return ServerResponse.createByError();
        }
        User user = userMapper.selectByPrimaryKey(userId);
        return ServerResponse.createBySuccess(user);
    }

    public ServerResponse isAdmin(User user){

        if (user != null && Const.Role.ROLE_ADMIN == user.getRole()){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();

    }


}

